package api

import (
	"bbs-go/internal/models"
	"bbs-go/internal/pkg/errs"
	"bbs-go/internal/pkg/room"
	"bbs-go/internal/services"
	"encoding/json"

	"github.com/kataras/iris/v12"
	"github.com/mlogclub/simple/web"
)

type ChatSocketController struct {
	Ctx iris.Context
}

// 好友聊天
func (c *ChatSocketController) Get() *web.JsonResult {
	user := services.UserTokenService.GetWsCurrent(c.Ctx)
	if user == nil {
		return web.JsonError(errs.NotLogin)
	}

	conn, err := room.Upgrader.Upgrade(c.Ctx.ResponseWriter(), c.Ctx.Request(), nil)
	if err != nil {
		return web.JsonError(err)
	}

	client := &room.Client{
		UserId:   int(user.Id),
		Conn:     conn,
		Send:     make(chan []byte, 256),
		Room:     room.GlobalRoom,
		Nickname: user.Nickname,
		Avatar:   user.Avatar,
	}

	room.GlobalRoom.Join <- client

	go client.Read()
	go client.Write()

	// 获取通知数据，推送给用户
	// 1.好友申请通知
	count, _ := services.ChatFriendsRequestService.GetUntreatedRequestCount(user.Id)
	// 2.好友消息通知
	friendUnReadList, _ := services.ChatFriendsMessagesService.GetFriendMessageUnReadCount(user.Id)
	// 3.群组消息通知
	groupUnReadList, _ := services.ChatGroupsMembersUnreadMessageService.GetGroupsMessageUnReadList(user.Id)

	// 查询群消息未读List
	noticeMessage := models.NoticeMessage{
		UserId:                 int(user.Id),
		UserNickname:           user.Nickname,
		FriendApplicationCount: count,
		FriendMessageNotice:    friendUnReadList,
		GroupMessageNotice:     groupUnReadList,
	}
	wsMessage := models.WsMessage{
		MessageType: 5,
		MessageData: noticeMessage,
	}
	bytes, _ := json.Marshal(wsMessage)
	// client.Send <- []byte(`{"messageType": 5,"messageData":{"userId": ` + strconv.FormatInt(user.Id, 10) + `, "userNickname": "` + user.Nickname + `"}}`)
	client.Send <- bytes

	return web.JsonData(models.Result{
		Result: true,
	})
}

func (c *ChatSocketController) GetClientList() *web.JsonResult {
	clientNames := []string{}
	for _, v := range room.GlobalRoom.Clients {
		clientNames = append(clientNames, v.Nickname)
	}
	return web.JsonData(clientNames)
}

// // 离开聊天室
// func (c *ChatMessageController) PostLive() *web.JsonResult {
// 	user := services.UserTokenService.GetCurrent(c.Ctx)
// 	if user == nil {
// 		return web.JsonError(errs.NotLogin)
// 	}

// 	conn, err := room.Upgrader.Upgrade(c.Ctx.ResponseWriter(), c.Ctx.Request(), nil)
// 	if err != nil {
// 		return web.JsonError(errs.NotLogin)
// 	}

// 	client := &room.Client{
// 		Types:    1, // 好友聊天
// 		Id:       int(user.Id),
// 		Conn:     conn,
// 		Send:     make(chan []byte, 256),
// 		Room:     room.GlobalRoom,
// 		Nickname: user.Nickname,
// 	}

// 	room.GlobalRoom.Leave <- client

// 	go client.Read()
// 	go client.Write()

// 	return web.JsonSuccess()
// }
